<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;padding: 15px 20px;background-color: #f8f9fa;border-radius: 6px;">
        <el-form :inline="true" class="search-form">
          <el-form-item label="源货币">
            <el-select v-model="source_currency" placeholder="请选择源货币" style="width: 120px;" clearable>
              <el-option
                v-for="currency in currencies"
                :key="currency"
                :label="currency"
                :value="currency"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="目标货币">
            <el-select v-model="target_currency" placeholder="请选择目标货币" style="width: 120px;" clearable>
              <el-option
                v-for="currency in currencies"
                :key="currency"
                :label="currency"
                :value="currency"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="is_active" placeholder="请选择状态" style="width: 120px;" clearable>
              <el-option label="全部" value="" />
              <el-option label="启用" value="true" />
              <el-option label="禁用" value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
            <el-button type="success" icon="el-icon-plus" :disabled="listLoading" @click="handleAction('create', '添加')">添加汇率</el-button>
            <el-button type="info" icon="el-icon-money" :disabled="listLoading" @click="showRateConverter">汇率转换</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @sort-change="handleSort"
        >
          <el-table-column prop="source_currency" label="源货币" width="120" />
          <el-table-column prop="target_currency" label="目标货币" width="120" />
          <el-table-column prop="exchange_rate" label="汇率" width="150">
            <template slot-scope="scope">
              <span style="color: #409EFF; font-weight: bold;">{{ scope.row.exchange_rate }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="note" label="备注" min-width="200">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.note" placement="top">
                <div>{{ scope.row.note }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="is_active" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.is_active ? 'success' : 'danger'"
                effect="dark"
              >
                {{ scope.row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建人" width="120" />
          <el-table-column prop="update_at" label="更新时间" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.update_at }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleAction('edit', scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <!-- 添加/编辑汇率对话框 -->
    <el-dialog
      :title="action === 'create' ? '添加汇率' : '编辑汇率'"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @closed="handleDialogClose"
    >
      <el-form ref="rateForm" :model="rateForm" :rules="rateRules" label-width="120px">
        <el-form-item label="源货币" prop="source_currency">
          <el-select v-model="rateForm.source_currency" placeholder="请选择源货币" style="width: 100%;">
            <el-option
              v-for="currency in currencies"
              :key="currency"
              :label="currency"
              :value="currency"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标货币" prop="target_currency">
          <el-select v-model="rateForm.target_currency" placeholder="请选择目标货币" style="width: 100%;">
            <el-option
              v-for="currency in currencies"
              :key="currency"
              :label="currency"
              :value="currency"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="汇率" prop="exchange_rate">
          <el-input-number
            v-model="rateForm.exchange_rate"
            :precision="4"
            :step="0.0001"
            :min="0"
            style="width: 100%;"
            placeholder="请输入汇率"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="rateForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch
            v-model="rateForm.is_active"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 汇率转换对话框 -->
    <el-dialog
      title="汇率转换"
      :visible.sync="converterVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="converterForm" :model="converterForm" label-width="120px">
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="converterForm.amount"
            :precision="2"
            :step="1"
            :min="0"
            style="width: 100%;"
            placeholder="请输入金额"
          />
        </el-form-item>
        <el-form-item label="源货币" prop="source_currency">
          <el-select v-model="converterForm.source_currency" placeholder="请选择源货币" style="width: 100%;">
            <el-option
              v-for="currency in currencies"
              :key="currency"
              :label="currency"
              :value="currency"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标货币" prop="target_currency">
          <el-select v-model="converterForm.target_currency" placeholder="请选择目标货币" style="width: 100%;">
            <el-option
              v-for="currency in currencies"
              :key="currency"
              :label="currency"
              :value="currency"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="convertLoading" @click="handleConvert">转换</el-button>
        </el-form-item>
        <el-form-item v-if="convertResult" label="转换结果">
          <el-alert
            :title="`${convertResult.source_amount} ${convertResult.source_currency} = ${convertResult.target_amount} ${convertResult.target_currency}`"
            type="success"
            :closable="false"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="converterVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, ConvertRate, GetCurrencyPairs } from '@/api/crm/crmexchangerate'
import qs from 'qs'

export default {
  name: 'CRMExchangeRate',
  data() {
    return {
      // 列表相关
      listLoading: false,
      data: [],
      page: 1,
      pagesize: 20,
      total: 0,

      // 搜索相关
      source_currency: '',
      target_currency: '',
      is_active: '',

      // 对话框相关
      dialogVisible: false,
      action: '',
      submitLoading: false,

      // 表单相关
      rateForm: {
        source_currency: '',
        target_currency: '',
        exchange_rate: 0,
        note: '',
        is_active: true
      },

      // 验证规则
      rateRules: {
        source_currency: [
          { required: true, message: '请选择源货币', trigger: 'change' }
        ],
        target_currency: [
          { required: true, message: '请选择目标货币', trigger: 'change' }
        ],
        exchange_rate: [
          { required: true, message: '请输入汇率', trigger: 'blur' }
        ]
      },

      // 转换器相关
      converterVisible: false,
      convertLoading: false,
      converterForm: {
        amount: 0,
        source_currency: '',
        target_currency: ''
      },
      convertResult: null,

      // 货币列表
      currencies: ['USD', 'EUR', 'CNY', 'JPY', 'GBP', 'AUD', 'CAD', 'CHF', 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'RUB', 'BRL', 'INR', 'KRW', 'SGD', 'HKD', 'THB', 'MXN', 'ZAR', 'TRY', 'AED', 'SAR']
    }
  },

  created() {
    this.fetchData()
    this.fetchCurrencyPairs()
  },

  methods: {
    // 获取数据
    fetchData() {
      this.listLoading = true
      const params = {
        page: this.page,
        page_size: this.pagesize,
        source_currency: this.source_currency,
        target_currency: this.target_currency,
        is_active: this.is_active
      }

      Get(null, qs.stringify(params))
        .then(response => {
          if (response.success) {
            this.data = response.data.data || []
            this.total = response.data.total || 0
          } else {
            this.$message.error(response.message || '获取数据失败')
          }
        })
        .catch(error => {
          console.error('获取数据失败:', error)
          this.$message.error('获取数据失败')
        })
        .finally(() => {
          this.listLoading = false
        })
    },

    // 获取货币对
    fetchCurrencyPairs() {
      GetCurrencyPairs()
        .then(response => {
          if (response.success) {
            // 可以根据后端返回的货币对数据来更新货币列表
            console.log('货币对数据:', response.data)
          }
        })
        .catch(error => {
          console.error('获取货币对失败:', error)
        })
    },

    // 搜索
    handleSearch() {
      this.page = 1
      this.fetchData()
    },

    // 排序
    handleSort(sort) {
      // 根据需要实现排序逻辑
      console.log('排序:', sort)
    },

    // 分页
    handleSizeChange(size) {
      this.pagesize = size
      this.page = 1
      this.fetchData()
    },

    handlePageChange(page) {
      this.page = page
      this.fetchData()
    },

    // 操作处理
    handleAction(action, row) {
      this.action = action

      if (action === 'create') {
        this.rateForm = {
          source_currency: '',
          target_currency: '',
          exchange_rate: 0,
          note: '',
          is_active: true
        }
        this.dialogVisible = true
      } else if (action === 'edit') {
        this.rateForm = { ...row }
        this.dialogVisible = true
      } else if (action === 'delete') {
        this.$confirm('确定要删除这条汇率记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          Delete(row.id)
            .then(response => {
              if (response.success) {
                this.$message.success('删除成功')
                this.fetchData()
              } else {
                this.$message.error(response.message || '删除失败')
              }
            })
            .catch(error => {
              console.error('删除失败:', error)
              this.$message.error('删除失败')
            })
        })
      }
    },

    // 提交表单
    handleSubmit() {
      this.$refs.rateForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          const apiCall = this.action === 'create' ? Post(this.rateForm) : Put(this.rateForm.id, this.rateForm)

          apiCall
            .then(response => {
              if (response.success) {
                this.$message.success(this.action === 'create' ? '添加成功' : '更新成功')
                this.dialogVisible = false
                this.fetchData()
              } else {
                this.$message.error(response.message || '操作失败')
              }
            })
            .catch(error => {
              console.error('操作失败:', error)
              this.$message.error('操作失败')
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },

    // 对话框关闭
    handleDialogClose() {
      this.$refs.rateForm.resetFields()
    },

    // 显示转换器
    showRateConverter() {
      this.converterForm = {
        amount: 0,
        source_currency: '',
        target_currency: ''
      }
      this.convertResult = null
      this.converterVisible = true
    },

    // 汇率转换
    handleConvert() {
      if (!this.converterForm.amount || !this.converterForm.source_currency || !this.converterForm.target_currency) {
        this.$message.warning('请填写完整的转换信息')
        return
      }

      this.convertLoading = true
      ConvertRate(this.converterForm)
        .then(response => {
          if (response.success) {
            this.convertResult = response.data
          } else {
            this.$message.error(response.message || '转换失败')
          }
        })
        .catch(error => {
          console.error('转换失败:', error)
          this.$message.error('转换失败')
        })
        .finally(() => {
          this.convertLoading = false
        })
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.mt-pagination {
  float: right;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
